//
//  GKVideoCammer.m
//  GKVideoRecord
//
//  Created by Apple on 16/12/27.
//  Copyright © 2016年 郭凯. All rights reserved.
//

#import "GKVideoCammer.h"
#import <GPUImage/GPUImage.h>
#import "GPUImageBeautifyFilter.h"
#import <CoreMotion/CoreMotion.h>
#import "GPUImageMovieWriterEx.h"
@interface GKVideoCammer()
/**GPUImageVideoCamera*/
@property(nonatomic,strong)GPUImageVideoCamera *videoCamera;
/**音频设置*/
@property (nonatomic,strong)NSDictionary* videoSetting;
/**视频设置*/
@property (nonatomic,strong)NSDictionary* audioSetting;
/**文件写入对象*/
@property (nonatomic,strong) GPUImageMovieWriterEx* moverWriter;
/**文件路劲*/
@property (nonatomic,copy) NSString* videoPath;
/**计时器*/
@property (nonatomic,strong) NSTimer* timer;
/**当前视频记录的时间*/
@property (nonatomic,assign) CGFloat recordTime ;
/**美颜滤镜*/
@property (nonatomic,strong) GPUImageBeautifyFilter *beautifyFilter;
/**预览图层*/
@property (nonatomic,strong) GPUImageView* preview;

@end

@implementation GKVideoCammer

- (instancetype)initWithPreview:(GPUImageView*)preview;
{
    self = [super init];
    if (self) {
        self.maxRecordTime = 8;
        self.preview = preview;
        _cameraPosition = GKcamerapPositionFont;
        /**1.初始化GPUImageVideoCamera实例对象*/
        self.videoCamera = [[GPUImageVideoCamera alloc] initWithSessionPreset:AVCaptureSessionPreset640x480 cameraPosition:AVCaptureDevicePositionFront];
        self.videoCamera.outputImageOrientation = UIInterfaceOrientationPortrait;
        self.videoCamera.horizontallyMirrorFrontFacingCamera = YES;
        preview.fillMode = kGPUImageFillModePreserveAspectRatioAndFill;
        [self.videoCamera addAudioInputsAndOutputs];
        /**2.将 GPUImageView添加到生产链*/
        [self.videoCamera addTarget:preview];
        [self.videoCamera startCameraCapture];
        
        //**视频设置*/
        NSDictionary *compressDic = [NSDictionary dictionaryWithObjectsAndKeys:
                                     [NSNumber numberWithInt:820000],AVVideoAverageBitRateKey,
                                     @(30),AVVideoExpectedSourceFrameRateKey,
                                     nil];
        
        self.videoSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                                       AVVideoCodecH264, AVVideoCodecKey,
                                       [NSNumber numberWithInteger: 480], AVVideoWidthKey,
                                       [NSNumber numberWithInteger: 640], AVVideoHeightKey,
                                       AVVideoScalingModeResizeAspectFill,AVVideoScalingModeKey,
                                       compressDic,AVVideoCompressionPropertiesKey,
                                       nil];
        /**音频设置*/
        AudioChannelLayout channelLayout;
        memset(&channelLayout, 0, sizeof(AudioChannelLayout));
        channelLayout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
        self.audioSetting = [NSDictionary dictionaryWithObjectsAndKeys:
                                       [ NSNumber numberWithInt: kAudioFormatMPEG4AAC], AVFormatIDKey,//制定编码算法
                                       [NSNumber numberWithInt:2],AVNumberOfChannelsKey,//声道
                                       [ NSNumber numberWithFloat: 44100.0 ], AVSampleRateKey,//采样率
                                       [ NSData dataWithBytes:&channelLayout length: sizeof( AudioChannelLayout)], AVChannelLayoutKey,
                                       [ NSNumber numberWithInt: 64000], AVEncoderBitRateKey,//编码率
                                       nil];
    }
    return self;
}


/**
 开始录制
 */
-(void)startRecordWithCammerAngle:(CGFloat)angle beauty:(BOOL)beauty{
    NSString *path = [self getVideoFileSavePath];
    self.videoPath = path;
    unlink([path UTF8String]);
    _moverWriter = [[GPUImageMovieWriterEx alloc]initWithMovieURL:[NSURL fileURLWithPath:path] size:CGSizeMake(480, 640)fileType:AVFileTypeQuickTimeMovie outputSettings:self.videoSetting];
    _moverWriter.encodingLiveVideo = YES;
    [_moverWriter setHasAudioTrack:YES audioSettings:self.audioSetting];
    
    self.videoCamera.audioEncodingTarget = _moverWriter;
    if (!beauty) {
        [self.videoCamera addTarget:self.moverWriter];
    }else{
        [self.beautifyFilter addTarget:self.moverWriter];
    }
    CGAffineTransform affineTransform =  CGAffineTransformMakeRotation(angle);
    [self.moverWriter startRecordingInOrientation:affineTransform];
    self.recording = YES;
    //开始定时器
    [self startTime];

}
/**
 暂停录制
 */
-(void)pasueRecord{
    [_moverWriter pauseRecording];
    [self stopTimer];

}
/**
 恢复录制
 */
-(void)resumeRecord{
    [_moverWriter resumeRecording];
    [self startTime];
}

/**
 取消录制
 */
-(void)cancelRecord{
    [_moverWriter cancelRecording];
    self.recordTime = 0;
    self.recording = NO;
    self.finishRecording = NO;
    [self stopTimer];//停止定时器
    [self removeFile:self.videoPath];

}

// 完成录制
-(void)finishedVideoRecord{
    NSLog(@"完成视频录制");
    [self.moverWriter finishRecording];
    [self closeFlash];//关闭闪关灯
    [self stopTimer];
    self.finishRecording = YES;
    self.recording = NO;
    self.recordTime = 0;
}
/**获取文件名 生成文件保存路径*/
-(NSString *)getVideoFileSavePath{
    NSString *videoName = [self getUploadFile_type:@"vidoe" fileType:@"mp4"];
    return [[self getVideoFloderCachePath] stringByAppendingString:[NSString stringWithFormat:@"/%@",videoName]];
}

//获得视频存放文件夹地址
-(NSString *)getVideoFloderCachePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).lastObject stringByAppendingString:@"/miaoyingVideos"];
    // 创建文件夹
    if (![fileManager fileExistsAtPath:path]) {
        [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return path;
}
- (NSString *)getUploadFile_type:(NSString *)type fileType:(NSString *)fileType {
    NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"HHmmss"];
    NSDate * NowDate = [NSDate dateWithTimeIntervalSince1970:now];
    NSString * timeStr = [formatter stringFromDate:NowDate];
    NSString *fileName = [NSString stringWithFormat:@"%@_%@.%@",type,timeStr,fileType];
    return fileName;
}


/**开启定时器*/
-(void)startTime{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
        self.recordTime += 0.01;
         CGFloat progress =  self.recordTime /_maxRecordTime;
        if (self.videoRecordProgress) {
            self.videoRecordProgress(progress);
        }
        if (self.recordTime >=_maxRecordTime) {
            [self finishedVideoRecord];
            if ([self.delegate respondsToSelector:@selector(videoRecordFinished)]) {
                [self.delegate videoRecordFinished];
            }
        }
    }];
}


/**停止定时器*/
-(void)stopTimer{
    [self.timer invalidate];
    self.timer = nil;
}

/**关闭闪关灯*/
-(void)closeFlash{
    if (self.videoCamera.inputCamera.torchMode == AVCaptureTorchModeOn) {
        [self.videoCamera.inputCamera lockForConfiguration:nil];
        self.videoCamera.inputCamera.torchMode = AVCaptureTorchModeOff;
        self.videoCamera.inputCamera.flashMode = AVCaptureTorchModeOff;
        [self.videoCamera.inputCamera unlockForConfiguration];
    }
}

// 开启闪关灯
-(void)openFlash{
    if (self.videoCamera.inputCamera.torchMode == AVCaptureTorchModeOff) {
        [self.videoCamera.inputCamera lockForConfiguration:nil];
        self.videoCamera.inputCamera.torchMode = AVCaptureTorchModeOn;
        self.videoCamera.inputCamera.flashMode = AVCaptureFlashModeOn;
        [self.videoCamera.inputCamera unlockForConfiguration];
    }
}
//切换前后摄像头
-(void)rotateCamera{
    [self.videoCamera rotateCamera];
    [self closeFlash];
    if (self.videoCamera.cameraPosition == AVCaptureDevicePositionBack) {
        _cameraPosition = GKcamerapPositionBack;
    }else if (self.videoCamera.cameraPosition == AVCaptureDevicePositionFront){
       _cameraPosition = GKcamerapPositionFont;
    }else{
        _cameraPosition = GKcamerapPositionUknow;
    }
}
/**
 开启美颜功能
 */
-(void)openBeauty{
    [self.videoCamera removeAllTargets];
    GPUImageBeautifyFilter *beautifyFilter = [[GPUImageBeautifyFilter alloc] init];
    self.beautifyFilter = beautifyFilter;
    [self.videoCamera addTarget:beautifyFilter];
    [beautifyFilter addTarget:self.preview];
    if (self.moverWriter) {
        [self.beautifyFilter addTarget:self.moverWriter];
    }


}

/**
 关闭美颜功能
 */
-(void)closeBeauty{
    [self.videoCamera removeAllTargets];
    [self.videoCamera removeTarget:self.beautifyFilter];
    [self.videoCamera addTarget:self.preview];
    if (self.moverWriter) {
        [self.videoCamera addTarget:self.moverWriter];
    }
}

//删除已经存储的文件
-(void)removeFile:(NSString *)path{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:self.videoPath]) {
        BOOL result = [manager removeItemAtPath:path error:nil];
        if (result){
            NSLog(@"文件删除成功");
        }
    }
}

@end
